import json
import requests,base64,urllib
class Bdapi():
    def __init__(self) -> None:
        self.client_id = "CLn2uCUzeTYzaaEkmbSGzaiP"
        self.client_secret = "c1sRGYIIQLygznsI2OXPeT5i5tG71naD"

    def getToken(self):
        url = "https://aip.baidubce.com/oauth/2.0/token?client_id=%s&client_secret=%s&grant_type=client_credentials"%(self.client_id,self.client_secret)
        payload = ""
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        print(response.text)
        mes = json.loads(response.text)
        return mes['access_token']

    # # 文字识别接口
    def getmes(self, urlmes):
        token = self.getToken()
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=%s" %(token)
        payload = 'url=%s' % (urlmes)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        mes = json.loads(response.text)
        print("mes>>>>>",mes['words_result'])
        return mes['words_result']


    def get_file_content_as_base64(self,path, urlencoded=False):
        """
        获取文件base64编码
        :param path: 文件路径
        :param urlencoded: 是否对结果进行urlencoded
        :return: base64编码信息
        """
        with open(path,'rb') as f:
            content = base64.b64encode(f.read()).decode("utf8")
            if urlencoded:
                content = urllib.parse.quote_plus(content)
        return content

    def contentmes(self,path):
        token = self.getToken()
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+token
        payload = "image=%s"%(self.get_file_content_as_base64(path,True))
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        print(response.text,"text>>>>>>>>>>>>>>>>>>")
        return response.text

bd = Bdapi()
